package message;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQTopic;

import javax.jms.*;
import java.util.Objects;

/**
 * Created with Intel IDEA.
 * 消息的属性
 * @Auther: gjt
 * @Date: 2024/11/3 10:30
 */
public class MessageProperties implements MessageListener {

    private static String USERNAME = ActiveMQConnection.DEFAULT_USER;
    private static String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;
    private static String BROKER = ActiveMQConnection.DEFAULT_BROKER_URL;

    private static String TOPIC_NAME = "topic";
    @Override
    public void onMessage(Message message) {
        // 创建主题连接工厂
        TopicConnectionFactory conFactory = new ActiveMQConnectionFactory(USERNAME, PASSWORD, BROKER);

        /**
         *  消息的属性就像可以分配给一条消息的附件消息头一样
         *  属性值可以是 byte, boolean, short, int, long, float, double, String
         *  三种基本类型： 应用程序特定的属性，JMS定义的属性和提供者特定的属性。
         */

        try {
            TopicConnection topicConnection = conFactory.createTopicConnection();
            if(Objects.isNull(topicConnection)){
                System.out.println("topicConnection is null");
            }


            TopicSession topicSession = topicConnection.createTopicSession(true, Session.AUTO_ACKNOWLEDGE);
            Topic topic = new ActiveMQTopic(TOPIC_NAME);
            TopicPublisher publisher = topicSession.createPublisher(topic);

            /**
             * 应用程序特定的属性：在消息传送之前进行设定。
             */
            TextMessage textMessage = topicSession.createTextMessage();
            textMessage.setText("hello world");
            textMessage.setStringProperty("name", "gjt");
            publisher.publish(textMessage);
            textMessage.setLongProperty("age", 15l);
            textMessage.clearProperties();// 清空所有属性

            // 注意 在获取属性时 检测是否存在
            if(textMessage.propertyExists("age")){
                System.out.println("存在属性");
            }else {
                System.out.println("不存在属性");
            }
        } catch (JMSException e) {
            throw new RuntimeException(e);
        }

    }
}
